<template>
  <el-dialog
    title="考生设置"
    width="560px"
    :visible.sync="dialogFormVisible"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="form"
      label-position="right"
      label-width="80px"
      v-loading="confirmLoading"
    >
      <el-form-item label="考试期数" prop="examId">
        <el-select
          v-model="form.examId"
          style="width: 100%"
          placeholder="请选择"
          @change="changePeriod"
        >
          <el-option
            v-for="item in examPeriodList"
            :key="item.id"
            :label="item.period"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考生来源" prop="fromInterface">
        <el-select
          v-model="form.fromInterface"
          style="width: 100%"
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in sourceList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择类型" prop="parentType">
        <el-col :span="11">
          <el-form-item prop="parentType" style="margin-bottom: 0;">
            <el-select
              v-model="form.parentType"
              style="width: 100%"
              placeholder="请选择"
              disabled
            >
              <el-option
                v-for="(item, index) in examTypes"
                :key="index"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="examTypes" style="margin-bottom: 0;">
            <el-select
              v-model="form.examTypes"
              style="width: 100%"
              placeholder="请选择"
              multiple
            >
              <el-option
                v-for="(item, index) in examCfgList"
                :key="index"
                :label="item.targetRoleName"
                :value="item.targetRole"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="选择考生" prop="examId">
        <el-col :span="11">
          <el-form-item prop="startTime">
            <el-date-picker
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="创建日期"
              v-model="form.startTime"
              style="width: 100%;"
              :picker-options="pickerOptionsStart"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="endTime">
            <el-date-picker
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期"
              v-model="form.endTime"
              style="width: 100%;"
              :picker-options="pickerOptionsEnd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        取消
      </el-button>
      <el-button type="primary" :loading="confirmLoading" @click="submitForm">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import formMixin from "@/mixins/form";
import request from "@/utils/request";
const sourceList = [
  { label: "接口导入", value: "1" },
  { label: "Excel导入", value: "0" },
  { label: "接口与Excel导入", value: "2" }
];
export default {
  name: "Dialog",
  mixins: [formMixin],
  components: {},
  data() {
    return {
      rules: {
        examId: [
          {
            required: true,
            message: "请选择考试期数",
            trigger: "change"
          }
        ],
        parentType: [
          {
            required: true,
            message: "请选择",
            trigger: "change"
          }
        ],
        fromInterface: [
          {
            required: true,
            message: "请选择考生数据来源",
            trigger: "change"
          }
        ]
      },
      Urls: {
        addUrl: "/api/examUser/examinfo/set",
        examPeriodListUrl: "/api/exam/list",
        getByIdUrl: "/api/exam/detail/get/",
        duplicateUrl:'/api/examUser/duplicate/query',
        exportExcelUrl: '/api/examUser/duplicate/export'
      },
      examPeriodList: [],
      sourceList,
      tipMap: {
        create: "设置成功"
      },
      examTypes: [
        {
          key: 'SAFETY_NEW',
          value: '安管人员新办'
        },
        {
          key: 'SAFETY_DELAY',
          value: '安管人员延期'
        },
        {
          key: 'SPECIAL_EQP',
          value: '特种设备'
        },
      ],
      examCfgList: [],
      fileExt: '.xls',
    };
  },
  computed: {},
  watch: {},
  methods: {
    changePeriod(val) {
      for (var i = 0; i < this.examPeriodList.length; i++) {
        if (this.examPeriodList[i].id === val) {
          this.form.examPeriod = this.examPeriodList[i].period
          break
        }
      }
      this.getDetail(val)
    },
    beforeOpen() {
      this.getExamPeriodList();
    },
    resetForm() {
      this.form = {};
    },
    // 获取考试期数
    getExamPeriodList() {
      request({
        url: this.Urls.examPeriodListUrl,
        method: "get"
      })
        .then(res => {
          console.log("period list", res);
          if (res.code == 0) {
            this.examPeriodList = res.data.records || [];
          } else {
            that.$notify({
              title: "提示",
              message: res.msg,
              type: "error",
              duration: 2000
            });
          }
        })
        .catch(err => {});
    },
    formatData(data) {
      let form = Object.assign({}, data);
      form.fromInterface == "2" ? null : form.fromInterface;
      return form;
    },
    getDetail(id) {
      this.confirmLoading = true
      request({
          url: this.Urls.getByIdUrl + id,
          method: "get"
        })
        .then(res => {
          this.confirmLoading = false
          if (res.code == 0) {
            this.examCfgList = res.data.examCfgList || []
            this.form.parentType = res.data.type
          } else {
            that.$notify({
              title: "提示",
              message: res.msg,
              type: "error",
              duration: 2000
            });
          }
        })
        .catch(err => {
          this.confirmLoading = false
        });
    },
    submitForm() {
      let that = this
      console.log('form', that.form)
      that.$refs["dataForm"].validate(valid => {
        if (valid) {
          let formData = that.formatData(that.form)
          that.confirmLoading = true
          request({
            url: that.Urls.duplicateUrl,
            method: 'post',
            data: {
              startTime: formData.startTime,
              endTime: formData.endTime,
              examId: formData.examId,
              parentType: formData.parentType,
              examTypes: formData.examTypes,
            }
          }).then((res) => {
            if (res.code == 0) {
              if(res.data) {
                const h = that.$createElement;
                that.$msgbox({
                  title: '提示',
                  message: h('p', null, [
                    h('span', null, '当前有考生已设置考试期数，点击“确定”将会覆盖原有考试信息，即会将重复考生安排到此次考试。如需部分修改请点击“取消”按钮，并下载'),
                    h('a', { style: 'color: teal',on: {
                      click: () => {
                        that.handleExport(formData)
                      }
                    } }, '已设置的重复考生名单'),
                    h('span', null, '，到考生管理中逐个修改。 ')
                  ]),
                  showCancelButton: true,
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                      instance.confirmButtonLoading = true;
                      instance.confirmButtonText = '执行中...';
                      that.automaticSubmit(formData)
                      instance.confirmButtonLoading = false;
                      } else {
                        this.$message({
                          type: 'info',
                          message: '已取消'
                        })
                        done();
                      }
                  }
                }).then(action => {

                })
              } else {
                that.automaticSubmit(formData)
              }
            } else {
              that.$notify({
                title: '提示',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      });
    },
    handleExport(formData) {
      const _this = this
      request({
        url: _this.Urls.exportExcelUrl,
        method: 'post',
        data: {
          startTime: formData.startTime,
          endTime: formData.endTime,
          examId: formData.examId,
          parentType: formData.parentType,
          examTypes: formData.examTypes,
        },
        responseType: 'blob'
      }).then(res => {
        _this.confirmLoading = false
        if (!res) {
          return
        }
        const blob = new Blob([res])
        let fileName = '重复考生' + _this.fileExt
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      }).catch(() => {
        _this.confirmLoading = false
      })
    },
    automaticSubmit(formData) {
      let that = this
      let url = {
        update: that.Urls.editUrl + that.form.id,
        create: that.Urls.addUrl
      }
      request({
        url: url[that.dialogStatus],
        method: 'post',
        data: formData
      }).then((res) => {
        console.log('res form', res)
        that.confirmLoading = false
        if (res.code == 0) {
          that.$notify({
            title: '提示',
            message: that.tipMap[that.dialogStatus],
            type: 'success',
            duration: 2000
          })
          that.dialogFormVisible = false
          that.$parent.afterSubmit()
        } else {
          that.$notify({
            title: '提示',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      }).catch((err) => {
        that.confirmLoading = false
      })
    },
  },
  created() {},
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {}
};
</script>
<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>
